﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using EAGetMail;
using OpenPop.Mime;
using OpenPop.Pop3;
using Attachment = EAGetMail.Attachment;

namespace Business
{
    public class OilReport
    {
        public class OilReportHelper : Page
        {
            private string m_curpath = "";
            private string sampleID;
            private string status;

            public void Page_Load(object sender, EventArgs e)
            {
                string tempFolder = String.Format("{0}\\Mails", HttpContext.Current.Server.MapPath(""));
                m_curpath = tempFolder;
                RetrieveEmailList();
                ListMail();
            }

            private void ListMail()
            {
                string tempFolder = String.Format("{0}\\Mails", HttpContext.Current.Server.MapPath(""));
                m_curpath = tempFolder;
                string mailFolder = String.Format("{0}", m_curpath);
                if (!Directory.Exists(mailFolder))
                    Directory.CreateDirectory(mailFolder);


                string[] files = Directory.GetFiles(mailFolder, "*.eml");
                int count = files.Length;
                for (int i = 0; i < count; i++)
                {
                    string fullname = files[i];
                    var oMail = new Mail("TryIt");
                    oMail.Load(fullname, true);
                    string s = Server.HtmlEncode(oMail.From.ToString());
                    if (s.Length == 0)
                        s = "[no sender]";
                    string subject2 = Server.HtmlEncode(oMail.Subject);
                    string subject = subject2.Replace(" ", "");
                    string[] sArray = subject.Split(new char[2] {'[', ']'});
                    var samplearray = new string[10];
                    int m = 0;
                    foreach (string str in sArray)
                    {
                        string getparts = str;
                        if (getparts != "" && getparts != "ALERT" && getparts != " ")
                        {
                            samplearray[m] = getparts;
                            m++;
                        }
                    }
                    oMail.Load(fullname, true);
                    string uin = getUIN(fullname);
                    string sampleddate = getSampledate(fullname);

                    if (uin != "")
                    {
                        samplearray[7] = uin;
                    }
                    string attachmentlink = GetAttachmentLink(fullname);
                    if (attachmentlink != "")
                    {
                        samplearray[8] = attachmentlink;
                    }

                    if (sampleddate != "")
                    {
                        samplearray[9] = sampleddate;
                    }
                    MatchSample(samplearray);
                    oMail.Clear();
                }
            }

            private void MatchSample(string[] sampleInfo)
            {
                sampleID = sampleInfo[4];
                string uinNO = sampleInfo[7];
                status = sampleInfo[5];
                string attachmentlink = sampleInfo[8];
                string sampledate = sampleInfo[9];
                string select_query2 = "SELECT o.Component_id,o.id, c.Value FROM OilReports o join ComponentTechnicalData c on"
                                       + " o.Component_id=c.Component_id WHERE (o.tested_date"
                                       + "=convert(datetime,'" + sampledate + "',103)) and (c.Value='" + uinNO +
                                       "' or c.Value='" + sampleID + "') and (c.Attribute='uin' OR c.Attribute='UIN')";

                var objcon = new CreateConn();
                DataTable dt = objcon.SQLConnDataTable(select_query2);
                if (dt != null && dt.Rows.Count > 0)
                {
                    try
                    {
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                string id = dr["id"].ToString();
                                string uinOrsf = dr["Value"].ToString();
                                double Num;
                                bool isnum = double.TryParse(uinOrsf.Trim(), out Num);
                                if (isnum)
                                {
                                    string update_UIN = "Update ComponentTechnicalData set Value='" + uinNO +
                                                        "' WHERE (Attribute='UIN' or Attribute='uin') and Component_id IN (SELECT Component_id FROM OilReports WHERE id='" +
                                                        id + "')";
                                    var objcon2 = new CreateConn();
                                    objcon2.SQLConnDataTable(update_UIN);
                                }
                                string modify_query = "Update OilReports set sample_id='" + sampleID + "', reportlink='" +
                                                      attachmentlink + "',status='" + status + "' WHERE id='" + id + "'";
                                var objcon_modify = new CreateConn();
                                objcon_modify.SQLConnDataTable(modify_query);
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }

            private string GetAttachmentLink(string emlFile)
            {
                var oMail = new Mail("TryIt");
                oMail.Load(emlFile, false);
                string attname = "";
                Attachment[] atts = oMail.Attachments;
                int count = atts.Length;
                if (count > 0)
                {
                    for (int i = 0; i < count; i++)
                    {
                        Attachment att = atts[i];
                        string tempFolder = String.Format("{0}\\Mails", HttpContext.Current.Server.MapPath(""));
                        m_curpath = tempFolder;
                        attname = String.Format("attachment.aspx?name={0}&seq={1}", Server.UrlEncode(emlFile), i);
                        if (att.Name.IndexOf("pdf") != -1)
                        {
                            Directory.SetCurrentDirectory(m_curpath);
                            att.SaveAs(att.Name, true); //Test save as;
                            return att.Name;
                        }
                    }
                }
                return attname;
            }

            protected void RetrieveEmailList()
            {
                var client = new Pop3Client();
                try
                {
                    string mailsPath = AppDomain.CurrentDomain.BaseDirectory + "Mails\\";
                    if (!Directory.Exists(mailsPath))
                    {
                        Directory.CreateDirectory(mailsPath);
                    }
                    int port = int.Parse("110");
                    string hotName = "mail.i2iportal.com.au";
                    client.Connect(hotName, port, false);
                    string userName = "oil@i2iportal.com.au";
                    string password = "wk733567d";
                    client.Authenticate(userName, password, AuthenticationMethod.Auto);
                    var list = FetchAllMessages(hotName, port, false, userName, password);
//                    var list = client.ListMessages(EnvelopeParts.UniqueId | EnvelopeParts.SequenceNumber);
                    int messages = int.Parse("10");
                    if (list.Count < messages)
                        messages = list.Count;

                    for (int i = 0; i < messages; i++)
                    {
                        Message message = list[i];
                        string filename = mailsPath +message.Headers.Date + ".eml";
                        var file = new FileInfo(filename);
                        if (!File.Exists(filename))
                        {
                            message.Save(file);
                        }
                    }
                }
                finally
                {
                    client.Disconnect();
                }
            }

            public static List<Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
            {
                // The client disconnects from the server when being disposed
                using (Pop3Client client = new Pop3Client())
                {
                    // Connect to the server
                    client.Connect(hostname, port, useSsl);

                    // Authenticate ourselves towards the server
                    client.Authenticate(username, password);

                    // Get the number of messages in the inbox
                    int messageCount = client.GetMessageCount();

                    // We want to download all messages
                    List<Message> allMessages = new List<Message>(messageCount);

                    // Messages are numbered in the interval: [1, messageCount]
                    // Ergo: message numbers are 1-based.
                    for (int i = 1; i <= messageCount; i++)
                    {
                        allMessages.Add(client.GetMessage(i));
                    }

                    // Now return the fetched messages
                    return allMessages;
                }
            }


            private static string GetFilename(string uniqueId)
            {
                const string allowed = " .-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                var sb = new StringBuilder();
                foreach (char t in uniqueId)
                {
                    if (allowed.IndexOf(t) < 0)
                        sb.AppendFormat("_{0:X2}", (int) t);
                    else
                        sb.Append(t);
                }
                return sb.ToString();
            }

            private string getUIN(string emlFile)
            {
                var oMail = new Mail("TryIt");
                oMail.Load(emlFile, false);

                string html = oMail.HtmlBody;
                string uin = "";
                int startindex = html.IndexOf("Compartment UIN:");
                try
                {
                    string uin_pre = html.Substring(startindex + 16, 30);
                    string uin_2 = uin_pre.Replace(" ", "");
                    int endindex2 = uin_2.IndexOf('\r');
                    if (endindex2 == -1)
                    {
                        endindex2 = uin_2.IndexOf('<');
                    }
                    string uin_result = uin_2.Substring(0, endindex2);
                    uin = uin_result;
                }
                catch (Exception e)
                {
                }
                return uin;
            }

            private string getSampledate(string emlFile)
            {
                var oMail = new Mail("TryIt");
                oMail.Load(emlFile, false);

                string html = oMail.HtmlBody;
                string uin = "";
                int startindex = html.IndexOf("Date sampled:");
                int endindex = html.IndexOf("Severity");
                try
                {
                    string uin_pre = html.Substring(startindex, endindex - startindex);
                    string uin_2;
                    uin_2 = uin_pre.Replace(" ", "");
                    int endindex2 = uin_2.IndexOf('\r');
                    if (endindex2 == -1)
                    {
                        endindex2 = uin_2.IndexOf('<');
                    }
                    uin = uin_2.Substring(12, endindex2 - 12);
                }
                catch (Exception e)
                {
                }
                return uin;
            }
        }
    }
}
